<template>
    <div>
      <video ref="videoElement" controls muted autoplay playsinline></video>
    </div>
  </template>
  
  <script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';
import flvjs from 'flv.js';

const videoElement = ref(null);
const flvPlayer = ref(null);
const ws = ref(null); // WebSocket 实例

const initPlayer = () => {
  if (!flvjs.isSupported()) return;

  // 创建WebSocket连接
  ws.value = new WebSocket('ws://172.30.30.89:559/openUrl/vsigI1TPnmo4f5d166d0b994006b6df9');

  // 接收文本数据并转换为ArrayBuffer
  ws.value.onmessage = (event) => {
    console.log(event);
    
    if (typeof event.data === 'string') {
      const base64Data = event.data;
      const binaryData = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
      flvPlayer.value.dispatch(new ArrayBuffer(binaryData.buffer));
    }
  };

  // 初始化FLV播放器
  flvPlayer.value = flvjs.createPlayer({
    type: 'flv',
    isLive: true,
    url: 'ws://dummy', // 此处URL无意义，仅占位
  });

  flvPlayer.value.attachMediaElement(videoElement.value);
  flvPlayer.value.load();
};
  // 销毁播放器
  const destroyPlayer = () => {
    if (flvPlayer.value) {
      flvPlayer.value.pause()
      flvPlayer.value.unload()
      flvPlayer.value.detachMediaElement()
      flvPlayer.value.destroy()
      flvPlayer.value = null
    }
  }
  
  // 生命周期
  onMounted(() => {
    initPlayer()
  })
  
  onBeforeUnmount(() => {
    destroyPlayer()
  })
  </script>
  
  <style scoped>
  video {
    width: 100%;
    max-width: 800px;
    background: #000;
  }
  </style>